package org.struts.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.struts.action.XMLBean;


public class Struts_Xml {
	
	public static Map<String,XMLBean> readStrutsXml(String xmlpath) throws JDOMException, IOException{
		Map<String,XMLBean> map = new HashMap<String,XMLBean>();
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(new File(xmlpath));
		Element root = doc.getRootElement();
		Element form = root.getChild("formbeans");
		List<Element> beans = form.getChildren();
		for(Element bean:beans){
			XMLBean xmlBean = new XMLBean();
			xmlBean.setBeanType(bean.getAttributeValue("type"));
			String name = bean.getAttributeValue("name");
			xmlBean.setActionName(name);
			Element mapping = root.getChild("action-mapping");
			List<Element> actions = mapping.getChildren();
			for(Element action:actions){
				String actionName = action.getAttributeValue("name");
				if(actionName.equals(name)){
					xmlBean.setActionType(action.getAttributeValue("type"));
					xmlBean.setActionPath(action.getAttributeValue("path"));
					List<Element> forwards = action.getChildren();
					Map<String, String> forwardMap = new HashMap<String, String>();
					for(Element forward:forwards){
						forwardMap.put(forward.getAttributeValue("name"), forward.getText());
					}
					xmlBean.setForwardMap(forwardMap);
					break;
				}				
			}
			
			map.put(xmlBean.getActionPath(), xmlBean);
		}		
		
		return map;
	}
	
	
	
}
